package com.bw.service.impl;

import com.bw.dao.impl.ReturnDaoImpl;
import com.bw.pojo.ReturnGoods;
import com.bw.pojo.vo.ReturnVo;
import com.bw.service.ReturnService;
import com.bw.util.JDBCUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.util.ArrayList;

public class ReturnServiceImpl implements ReturnService {
    ReturnDaoImpl dao = new ReturnDaoImpl();
    @SneakyThrows
    @Override
    public void returnPurchase(ReturnVo returnVo) {
        /**
         * 1.获取连接
         * 2.关闭自动开启手动
         * 3.事务： 3.1：像库存表添加数据 3.2 循环 向中间表表添加数据 3.3修改中间表达库存数量
         * 4.成功：提交事务
         * 5.失败：回滚
         * 6.开启自动 关闭
         */
        Connection conn = null;
        try {
            conn = JDBCUtil.getConn();
            conn.setAutoCommit(false);
            Integer goodsId =  dao.addRetrunPurchase(conn,returnVo);
            ArrayList<ReturnGoods> arr = returnVo.getArr();
            for (ReturnGoods returnGoods : arr) {
                dao.addReturnGoods(conn,goodsId,returnGoods.getReturnId(),returnGoods.getOutNum());
                dao.updRetrunGoods(conn,returnGoods.getOutNum(),returnGoods.getGoodsId());
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
        } finally {
            conn.setAutoCommit(true);
            conn.close();
        }
    }
}
